using Catalog.Application.CatalogItems.Interfaces;
using Catalog.Application.Contracts.DTOs;
using Microsoft.EntityFrameworkCore;

namespace Catalog.Infrastructure.Persistence.ReadServices;

public class CatalogItemReadService : ICatalogItemReadService
{
    private readonly CatalogDbContext _dbContext;

    public CatalogItemReadService(CatalogDbContext dbContext)
    {
        _dbContext = dbContext;
    }
    public async Task<bool> ExistsAsync(Guid id)
    {
        return await _dbContext.CatalogItems
            .AsNoTracking()
            .AnyAsync(b => b.Id == id);
    }

    public async Task<bool> ExistsByBrandIdAsync(Guid brandId)
    {
        return await _dbContext.CatalogItems
            .AsNoTracking()
            .AnyAsync(x => x.BrandId == brandId);
    }

    public async Task<CatalogItemProfileDto?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _dbContext.CatalogItems
            .AsNoTracking()
            .Where(x => x.Id == id)
            .Select(x => new CatalogItemProfileDto
            {
                Id = x.Id,
                Name = x.Name,
                Price = x.Price,
                Description = x.Description,
                BrandId = x.BrandId,
                CategoryId = x.CategoryId

            })
            .FirstOrDefaultAsync(cancellationToken);
    }

    public async Task<IEnumerable<CatalogItemProfileDto>> GetListAsync(string? keyword = null, CancellationToken cancellationToken = default)
    {
        var query = _dbContext.CatalogItems.AsNoTracking();

        if (!string.IsNullOrWhiteSpace(keyword))
        {
            query = query.Where(x => x.Name.Contains(keyword));
        }

        return await query
            .Select(x => new CatalogItemProfileDto
            {
                Id = x.Id,
                Name = x.Name,
                Price = x.Price,
                Description = x.Description,
                BrandId = x.BrandId,
                CategoryId = x.CategoryId

            })
            .ToListAsync(cancellationToken);
    }

    public async Task<IEnumerable<CatalogItemProfileDto>> GetPagedListAsync(int page, int pageSize, CancellationToken cancellationToken)
    {
        return await _dbContext.CatalogItems
            .AsNoTracking()
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .Select(x => new CatalogItemProfileDto
            {
                Id = x.Id,
                Name = x.Name,
                Price = x.Price,
                Description = x.Description,
                BrandId = x.BrandId,
                CategoryId = x.CategoryId
            })
            .ToListAsync(cancellationToken);
    }
}